var grid01 = $('#jgTable01'),
    grid02 = $('#jgTable02');

var Father = '', Father_Name = '', changedRows = [];

var postData02 = {
    Method: 'Q',
    Content:{
        Code: Father,
        SearchText: ''
    }
};
for(i in postData){
    postData02[i] = postData[i];
}

$(function(){
    gridInit01();
    gridInit02();
    $('li[data-opt="add"],#submitBtn').on('click', saveSubmit);
});

function gridInit01(){  //MDM0025/MDM002502
    var gridData01 = Object.create(gridData);
    gridData01.grid = $('#jgTable01');
    gridData01.pager = $('#jgPager01');
    gridData01.scroll = true;
    gridData01.height = '390px';
    gridData01.rownumbers = false;
    gridData01.url = mdmPath + '/MDM0025/MDM002502';
    gridData01.colModel = [
        {label:'代码', name:'Code', sortable:false, hidden:true},
        {label:'名称', name:'Name', sortable:false}
    ];
    gridData01.rowNum = 20;
    gridData01.sortname = 'Code';
    var postData01 = {
        Method: 'Q',
        Content: {
            SearchText: ''
        }
    };
    for(i in postData){
        postData01[i] = postData[i];
    }
    //console.log(postData)
    gridData01.beforeRequest = function(){
        gridData01.grid.jqGrid("setGridParam", {
            postData : postData01,
        });
    };
    gridData01.loadComplete = function(xhr){
        xhr.Status == -999 && alert_QX($('body'), xhr.Message);
        setTimeout(clickTr,200);
    };
    gridData01.onSelectRow = function(rowid,status){
        var rowData = grid01.jqGrid('getRowData', rowid);  
        //console.log(rowData)
        Father = rowData.Code;
        Father_Name = rowData.Name;
        postData02 = {
            Content: {
                Code: Father,
                SearchText: ''
            }
        }
        grid02.trigger('reloadGrid');
    };
    gridInit(gridData01);
}

function alarmFormatter(cellvalue, options, rowdata){
    switch(cellvalue){
        case 'N':
            cellvalue = '<span>无</span>';
        break;
        case 'F':
            cellvalue = '<span>有</span>';
        break;
        case 'P':
            cellvalue = '<span>部分</span>';
        break;
    }
    if(rowdata.Type == 2){
        cellvalue += '<a href="javascript:0" opt-data="_delete"><i class="glyphicon glyphicon-remove-circle" title="删除权限"></i></a>'+
        '&nbsp;<a href="javascript:0" opt-data="_add"><i class="glyphicon glyphicon-ok-circle" title="添加权限"></i></a>';
    }
    return cellvalue;
}
function gridInit02(){  //MDM0032/MDM003202
    grid02.jqGrid({
        styleUI : 'Bootstrap',
        height: 429,
        treeGrid: true, 
        datatype: "json",
        treeGridModel: "adjacency",
        ExpandColumn: "PermissionName",
        mtype: "post",
        url: mdmPath + "/MDM0032/MDM003202",
        colModel: [
            { label: '代码', name: 'Code', hidden:true},
            { label: "权限代码", name: "PermissionCode", hidden:true, key: true},
            { label: '权限名称', name: 'PermissionName'},
            { 
                label: '权限', name: 'Permission', 
                formatter: alarmFormatter
                // editable: true, 
                // edittype:'select', 
                // formatter: 'select',
                // editoptions:{
                //     value:{'N':'无','F':'有'},
                //     dataEvents:[
                //         {
                //             type: 'click',
                //             fn: function(){
                                
                //             }
                //         },
                //         {
                //             type: 'blur', 
                //             fn: function() {
                //                 console.log('blur')
                //                 var rowId = grid02.jqGrid('getGridParam', 'selrow');
                //                 var iRow = grid02.jqGrid('getInd', rowId, false);
                //                 var iCol = $(this).parent('td').index();
                //                 grid02.jqGrid('saveCell', iRow, iCol);
                //                 $(this).parent().attr('title',$(this).find('option:selected').text());
                //             }
                //         },
                //         {
                //             type: 'change',
                //             fn: function () {
                //                 var rowId = grid02.jqGrid('getGridParam', 'selrow');
                //                 var iRow = grid02.jqGrid('getInd', rowId, false);
                //                 var rowData = grid02.jqGrid('getRowData', rowId);
                //                 var value = $(this).val();
                //                 var tempData = {
                //                     'Code': Father,
                //                     'Name': Father_Name,
                //                     'PermissionCode': rowData.PermissionCode,
                //                     'Permission': value
                //                 };
                //                 $(this).parent().attr('title',$(this).find('option:selected').text());
                //                 changedRows.push(tempData);
                //             }
                //         } 
                //     ]
                // },
            },
            { label: '权限类型', name: 'Type', formatter: function(cellvalue, options, rowdata){
                switch(cellvalue){
                    case '1':
                        cellvalue = '节点';
                    break;
                    case '2':
                        cellvalue = 'Action';
                    break;
                    case '3':
                        cellvalue = '数据列';
                    break;
                }
                return cellvalue;
            }}
        ],
        jsonReader: {
            root: 'Content.rows'
        },
        beforeRequest: function(){
            grid02.jqGrid('setGridParam', {
                postData: postData02
            })
        },
        loadComplete: function(xhr){
            xhr.Status == -999 && alert_situ($('.u_row').find('.u_table_container'),re.Message);
            gridSize();
            $('a[opt-data="_add"]').unbind('click').bind('click', function(){
                $(this).parent().find('span').text('有');
            })
            $('a[opt-data="_delete"]').unbind('click').bind('click', function(){
                $(this).parent().find('span').text('无');
            })
        },
        cellEdit: true,
        cellsubmit: 'rclientArray'
    });
}

//Options
function saveSubmit(){
    var rowData = grid02.jqGrid('getRowData');
    //rowData = changedRows.concat(rowData).unique('PermissionCode');
    var requestData = [];
    rowData.forEach(function(v,i,a){
        //console.log(v);
        var pattern = new RegExp(/\<span\>(\S*)\<\/span\>/g);
        var idx = pattern.exec(v.Permission);
        //console.log(idx[1])
        if(idx[1] == '无'){
            var Permission = 'N'
        }else if(idx[1] == '有'){
            var Permission = 'F'
        }
        requestData.push({Code:Father, Name:Father_Name, PermissionCode:v.PermissionCode, Permission:Permission});
    });
    var _postData = {
        Method: 'U',
        Content: {
            Code: Father,
            Name: Father_Name,
            MDM003201: requestData
        }
    }
    for(i in postData) {
        _postData[i] = postData[i];
    }
    console.log(_postData)
    $.ajax({
        type: "post",
        url: mdmPath + "/MDM0032/MDM003201",
        data: _postData,
        dataType: "json",
        success: function (re) {
            if(re.Status == 200){
                myAlert('保存成功');
                // grid02.trigger('reloadGrid');
            }else{
                myAlert(re.Message);
            }
        }
    });
}

//Style
function gridSize(){
    grid02.setGridWidth($('.u_row .u_table_container').width());
}
function clickTr() {
    grid01.find('>tbody>tr:nth-child(2)').trigger('click');
}